package com.zc.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zc.edu.entity.Chapter;
import com.zc.edu.entity.Video;
import com.zc.edu.entity.vo.ChapterVo;
import com.zc.edu.mapper.ChapterMapper;
import com.zc.edu.mapper.VideoMapper;
import com.zc.edu.service.ChapterService;
import com.zc.servicebase.exception.CongException;
import com.zc.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author cong
 * @since 2022-11-25
 */
@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {

	@Autowired
	private VideoMapper videoMapper;

	@Override
	public List<ChapterVo> getAllChapter(String courseId) {
		QueryWrapper<Chapter> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("course_id", courseId);
		List<Chapter> chapterList = this.list(queryWrapper);
		List<ChapterVo> chapterVoList = new ArrayList<>();
		chapterList.forEach(chapter -> {
			ChapterVo chapterVo = new ChapterVo();
			BeanUtils.copyProperties(chapter,chapterVo);
			String chapterId = chapterVo.getId();
			if (!StringUtils.isEmpty(chapterId)) {
				QueryWrapper<Video> queryWrapperVideo = new QueryWrapper<>();
				queryWrapperVideo.eq("chapter_id", chapterId);
				List<Video> videoList = videoMapper.selectList(queryWrapperVideo);
				List<ChapterVo> videoVoList = new ArrayList<>();
				videoList.forEach(video -> {
					ChapterVo videoVo = new ChapterVo();
					BeanUtils.copyProperties(video, videoVo);
					videoVoList.add(videoVo);
				});
				chapterVo.setChildren(videoVoList);
			}
			chapterVoList.add(chapterVo);
		});
		return chapterVoList;
	}

	@Override
	public boolean deleteChapter(String chapterId) {
		QueryWrapper<Video> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("chapter_id", chapterId);
		Integer count = videoMapper.selectCount(queryWrapper);

		if (count > 0) {
			// 章节有小节，不删除
			throw  new CongException(R.error().getCode(), "章节下面有小节");
		} else {
			return this.removeById(chapterId);
		}
	}

	@Override
	public boolean removeChapter(String courseId) {
		QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
		wrapper.eq("course_id", courseId);
		boolean remove = this.remove(wrapper);
		return remove;
	}
}
